package com.tsinghuabigdata.edu.ddmath.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.constant.BaseConfig;
import com.tsinghuabigdata.edu.ddmath.module.apkupgrade.ApkLoader;
import com.tsinghuabigdata.edu.ddmath.module.apkupgrade.ApkUpgradeManager;
import com.tsinghuabigdata.edu.ddmath.module.apkupgrade.DownProgressObserver;
import com.tsinghuabigdata.edu.ddmath.module.apkupgrade.UpdateInfo;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.receive.NetworkStateRecevie;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.ActivityUtil;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;
import com.tsinghuabigdata.edu.ddmath.util.ScreenLock;
import com.umeng.analytics.MobclickAgent;

import cn.jpush.android.api.JPushInterface;

public class InitActivity extends Activity {

    private Context context;

    //APK upgrade
    DownProgressObserver downloadObserve;
    private ProgressDialog dialog;

    // 禁止锁屏，保持高亮
    private ScreenLock screenLock = ScreenLock.alloct();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        //UploadLogs.moveLogsAndUpload();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        setContentView(R.layout.activity_init);

        MobclickAgent.setDebugMode(true);

        NetworkStateRecevie.setNetWorkState(this);


        //设置代理开关
        Boolean useDns = AccountUtils.getDnsProxy();
        if (AppUtils.isRelease() && useDns != null) {
            BaseConfig.IS_USE_DNSPROXY = useDns;
        }

        //检查APK更新
        if (AppUtils.isDebug() ){//|| AppUtils.isBeta()) {
            //跳过更新检查
            launchApp();
        } else {
            checkApkUpdate();
        }
    }

    private void checkApkUpdate() {
        new LoginModel().checkApkupdate(new RequestListener<UpdateInfo>() {
            @Override
            public void onSuccess(UpdateInfo res) {
                startLoadApk(res);
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                if (AppUtils.isNoNetwork()) {
                    AlertManager.show(context, "没有检查到可用网络，请打开网络后再使用客户端！", "重试", "退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            checkApkUpdate();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                    return;
                }
//                // 更新检查失败，提示是否继续检查，否则退出
//                AlertManager.show(context, "连接失败，请重试或退出！", "重试", "退出", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        checkApkUpdate();
//                    }
//                }, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
//                    }
//                });
                launchApp();
            }
        });
    }

    private void openWelcomePager() {
        ActivityUtil.goActivity(this, WelcomeActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        screenLock.acquireWakeLock(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        screenLock.releaseWakeLock();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 禁止用户按返回键退出
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void launchApp() {
        new Handler() {
            @Override
            public void handleMessage(Message msg) {

//                if (isOpenWelcomePager()) {
//                    openWelcomePager();
//                    finish();
//                    return;
//                }

                ActivityUtil.goActivity(context, MainActivity.class);

                finish();
            }
        }.sendEmptyMessageDelayed(1, 500);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        //删除注册信息
        if (downloadObserve != null) {
            downloadObserve.unregisterObserver();
        }
    }

    public boolean isOpenWelcomePager() {
        return PreferencesUtils.getInt(this, AppConst.WELCOME_OPENED, 0) == 0;
    }

    private void startLoadApk(UpdateInfo latesApkUpdateinfo) {
        if (latesApkUpdateinfo == null) {
            launchApp();
            return;
        }

        UpdateInfo currentApkVersionInfo;
        currentApkVersionInfo = new UpdateInfo();
        currentApkVersionInfo.setVersion(AppUtils.getPackageInfo(context).versionName);
        currentApkVersionInfo.setVersionCode(AppUtils.getPackageInfo(context).versionCode);

        ApkUpgradeManager upgradeManager = ApkUpgradeManager.getInstance();
        if (!upgradeManager.isNeedUpdage(currentApkVersionInfo, latesApkUpdateinfo)) {
            launchApp();
            return;
        }

        AppLog.i("start load apk");
        //取APK URL
        String mApkUpdateUrl = latesApkUpdateinfo.getFilePath();

        //first 构建dialog提示信息
        String dstVer = latesApkUpdateinfo.getVersion();
        String destVerCode = latesApkUpdateinfo.getVersionCode() + "";
        String upgradeDesc = latesApkUpdateinfo.getUpdateDesc();
        String updateMessage = "有新版本了！版本号" + dstVer + "   \n更新内容" + upgradeDesc;

        upgradeManager.setUpdateMessage(updateMessage);

        //second
        ApkLoader apkLoader = new ApkLoader(context, mApkUpdateUrl, "apk");
        apkLoader.setNotifyTitle("豆豆数学");
        apkLoader.setNotifyDesc("正在下载更新包,请耐心等待下载完成.");
        apkLoader.setApkName("doudoumath" + "_" + dstVer + "_" + destVerCode + ".apk");
        upgradeManager.setApkLoader(apkLoader);
        upgradeManager.setCheckUpgradeListener(new ApkUpgradeManager.CheckUpgradeListener() {
            @Override
            public boolean isForceInstall() {
                //返回true则dialog取消变回退出， 只改变对话框取消按钮的文字
                AppLog.i("是否强制安装方法被调用");
                return false;
            }
        });
        upgradeManager.setDiaBtListener(new ApkUpgradeManager.DialogButtonListener() {
            @Override
            public void cancelAction(boolean isForce) {
                AlertManager.show(context, "取消被点击了");
                if (isForce) {
                    finish();
                } else {
                    launchApp();
                }
            }

            @Override
            public void installAfter() {
                AppLog.i("安装完成后被调用");
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        //初始化进度条
        // third
        dialog = upgradeManager.initProgressDialog(this);
        downloadObserve = new DownProgressObserver(null, context, dialog, apkLoader);
        downloadObserve.registerObserver();

        //start load and instal
        upgradeManager.checkUpgradeInfo(context, currentApkVersionInfo, latesApkUpdateinfo);
    }

}
